package com.niuwa.p2p.service.impl.fund;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.dao.fund.ChlAcctRuleDao;
import com.niuwa.p2p.dao.fund.CustAcctRuleDao;
import com.niuwa.p2p.dao.fund.PayChlRuleDao;
import com.niuwa.p2p.dao.fund.PayCustRuleDao;
import com.niuwa.p2p.dao.fund.PayPartnerDao;
import com.niuwa.p2p.dao.fund.PayPartnerDetailDao;
import com.niuwa.p2p.dao.fund.PayPartnerDetailFileDao;
import com.niuwa.p2p.dao.fund.PayPartnerFileDao;
import com.niuwa.p2p.dao.nwfile.NWFileDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.fund.ChlAcctRule;
import com.niuwa.p2p.entity.fund.CustAcctRule;
import com.niuwa.p2p.entity.fund.PayChlRuleKey;
import com.niuwa.p2p.entity.fund.PayCustRuleKey;
import com.niuwa.p2p.entity.fund.PayPartner;
import com.niuwa.p2p.entity.fund.PayPartnerDetail;
import com.niuwa.p2p.entity.fund.PayPartnerDetailFileKey;
import com.niuwa.p2p.entity.fund.PayPartnerFile;
import com.niuwa.p2p.entity.nwfile.NWFile;
import com.niuwa.p2p.service.fund.IPayPartnerService;
import com.niuwa.p2p.service.sequence.ISequenceService;
import com.niuwa.p2p.vo.fund.PayPartnerForm;

@Service
public class PayPartnerServiceImpl implements IPayPartnerService {

	@Autowired
	private PayPartnerDao partnerDao;
	
	@Autowired
	private PayPartnerDetailDao partnerDetailDao;
	
	@Autowired
	private PayPartnerDetailFileDao detailFileDao;
	
	@Autowired
	private ISequenceService sequenceService;
	
	@Autowired
	private ChlAcctRuleDao chlArDao;
	
	@Autowired
	private CustAcctRuleDao custArDao;
	
	@Autowired
	private PayPartnerFileDao payPartnerFileDao;
	
	@Autowired
	private PayChlRuleDao chlRuleDao;
	
	@Autowired
	private PayCustRuleDao custRuleDao;
	
	@Autowired
	private NWFileDao nwFileDao;
	
	@Override
	public PageBean<PayPartner> selectPartnerBySelective(
			Map<String, Object> paramMap) {
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		//协议生效日-开始时间
		String startTakeDate = (String) paramMap.get("startTakeDate");
		if (StringUtils.isNotBlank(startTakeDate))
			paramMap.put("startTakeDate", startTakeDate.concat(" 00:00:00"));
		//协议生效日-结束时间
		String endTakeDate = (String) paramMap.get("endTakeDate");
		if (StringUtils.isNotBlank(endTakeDate))
			paramMap.put("endTakeDate", endTakeDate.concat(" 23:59:59"));
		//协议到期日-开始时间
		String startDueDate = (String) paramMap.get("startDueDate");
		if (StringUtils.isNotBlank(startDueDate))
			paramMap.put("startDueDate", startDueDate.concat(" 00:00:00"));
		//协议到期日-结束时间
		String endDueDate = (String) paramMap.get("endDueDate");
		if (StringUtils.isNotBlank(endDueDate))
			paramMap.put("endDueDate", endDueDate.concat(" 23:59:59"));
		
		int totalCount = partnerDao.getPartnerCountByConditions(paramMap);
		PageBean<PayPartner> page = new PageBean<PayPartner>(totalCount);
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(partnerDao.getPartnerByConditions(paramMap));
		return page;
	}

	@Override
	public PayPartner selectByPrimaryKey(String partnerCode) {
		return partnerDao.selectByPrimaryKey(partnerCode);
	}

	@Override
	public int addPartnerDetail(PayPartnerDetail partnerDetail,
			List<Long> protFileID) throws Exception {
		//添加变更记录 p2p_pay_partner_detail
		int result = partnerDetailDao.insertPayPartnerDetail(partnerDetail);//返回记录ID
		Long id = partnerDetail.getId();
		if(result > 0){
			if(protFileID != null){
				for (Long fileId : protFileID) {
					PayPartnerDetailFileKey detailFileKey = new PayPartnerDetailFileKey();
					detailFileKey.setDetailId(id);
					detailFileKey.setFileId(fileId);
					//添加变更记录与文件关联表 p2p_pay_partner_detail_file
					result = detailFileDao.insertDetailFile(detailFileKey);
				}
			}
		}
		return result;
	}

	@Override
	public List<PayPartnerDetail> selectDetailByPartnerNo(String partnerCode) {
		return partnerDetailDao.selectDetailByPartnerNo(partnerCode);
	}

	@Override
	public void insert(PayPartnerForm form,List<Long> payPartnerFileID, long userId) throws Exception {
		//机构编号
		String partnerCode = sequenceService.getCompleteSequenceBySeqKey("TPOM");
		// 新增合作机构基本信息 
		this.insertPartner(partnerCode, form.getPartner(), payPartnerFileID, userId);
		// 新增客户规则信息
		this.inserCustAr(form.getCustr(), partnerCode);
		// 新增渠道规则信息
		this.insertChlAr(form.getChlr(), partnerCode);
		
	}
	
	@Override
	public void update(PayPartnerForm form, List<Long> payPartnerFileID, long userId) throws Exception {
		// 更新合作机构基本信息 
		this.updatePartner(form.getPartner(), payPartnerFileID, userId);
		//修改客户规则信息
		this.updateCustAr(form.getCustr(), form.getPartner());
		//修改渠道规则信息
		this.updateChlAr(form.getChlr(), form.getPartner());
	}
	
	/**
	 * 修改渠道规则信息
	 * @param chlr
	 */
	public void updateChlAr(ChlAcctRule chlr, PayPartner partner)  throws Exception{
		//免费充值额度限制
		String rechargeType = chlr.getRechargeType();
		//根据类型修改相应的值
		//可提现部分
		if("N".equalsIgnoreCase(chlr.getUsableWithdraw())){
			chlr.setWithdrawValue("");//可提现部分值
			//清空提现费率类型和对应的值
			chlr.setWithdrawType(null);//提现费率
			chlr.setWithdrawFixFee(null);//提现固定每笔收费
			chlr.setWithdrawStep(null);//提现阶段金额 
			chlr.setWithdrawStepFee(null);//提现阶段收费金额
			chlr.setWithdrawRate(null);//提现费率
		}
		//提现费率类型
		String withdrawType = chlr.getWithdrawType();
		//发送充值通知
		if("N".equalsIgnoreCase(chlr.getIsSendMsg())){
			chlr.setSendValue("");//发送通知值
		}
		//充值费率--费率
		if("PERCENT".equalsIgnoreCase(rechargeType)){
			chlr.setRechargeStep(null);//充值阶段金额 
			chlr.setRechargeStepFee(null);//充值阶段收费金额
			chlr.setRechargeFixFee(null);//充值固定每笔收费
		}
		//充值费率-- 固定值
		if("FIXED".equalsIgnoreCase(rechargeType)){
			chlr.setRechargeStep(null);//充值阶段金额 
			chlr.setRechargeStepFee(null);//充值阶段收费金额
			chlr.setRechargeRate(null);//充值费率
		}
		//充值费率--阶梯费率
		if("STEP".equalsIgnoreCase(rechargeType)){
			chlr.setRechargeRate(null);//充值费率
			chlr.setRechargeFixFee(null);//充值固定每笔收费
		}
		
		//提现费率--费率
		if("PERCENT".equalsIgnoreCase(withdrawType)){
			chlr.setWithdrawFixFee(null);//提现固定每笔收费
			chlr.setWithdrawStep(null);//提现阶段金额 
			chlr.setWithdrawStepFee(null);//提现阶段收费金额
		}
		//提现费率-- 固定值
		if("FIXED".equalsIgnoreCase(withdrawType)){
			chlr.setWithdrawStep(null);//提现阶段金额 
			chlr.setWithdrawStepFee(null);//提现阶段收费金额
			chlr.setWithdrawRate(null);//提现费率
		}
		//提现费率--阶梯费率
		if("STEP".equalsIgnoreCase(withdrawType)){
			chlr.setWithdrawFixFee(null);//提现固定每笔收费
			chlr.setWithdrawRate(null);//提现费率
		}
		//根据机构编号获取规则ID
		String chlRuleId = chlRuleDao.selectPayChlRuleByPartnerNo(partner.getPartnerCode());
		chlr.setId(Long.valueOf(chlRuleId));
		//修改规则
		chlArDao.updateByPrimaryKey(chlr);
	}
	
	/**
	 * 修改客户规则信息
	 * @param partner
	 * @param payPartnerFileID
	 * @param userId
	 */
	public void updateCustAr(CustAcctRule chlr, PayPartner partner)  throws Exception{
		//免费充值类型
		String isRechargeFree = chlr.getIsRechargeFree();
		//免费充值类型为N时，免费充值额度类型和额度清空
		if("N".equalsIgnoreCase(isRechargeFree)){
			chlr.setRechargeLimit("");
			chlr.setFreeAmount(null);
		}
		//免费提现类型
		String isWithdrawFree = chlr.getIsWithdrawFree();
		//免费提现类型为N时，免费提现额度值清空
		if("N".equalsIgnoreCase(isWithdrawFree)){
			chlr.setWithdrawLimit("");
		}
		//免费提现额度类型
		String withdrawLimit = chlr.getWithdrawLimit();
		if("N".equalsIgnoreCase(withdrawLimit)){
			chlr.setWithdrawType(null);//提现费率类型
			chlr.setWithdrawFixFee(null);//提现固定每笔收费
			chlr.setWithdrawStep(null);//提现阶段金额 
			chlr.setWithdrawStepFee(null);//提现阶段收费金额
			chlr.setWithdrawRate(null);//提现费率
		}
		//免费充值额度限制
		String rechargeLimit = chlr.getRechargeLimit();
		//根据类型修改相应的值
		//免费充值额度
		if("N".equalsIgnoreCase(rechargeLimit)){
			//清空免费充值额度值
			chlr.setFreeAmount(null);//免费充值额度值
			//清空充值费率类型和对应的值
			chlr.setRechargeType(null);//充值费率类型
			chlr.setRechargeStep(null);//充值阶段金额 
			chlr.setRechargeStepFee(null);//充值阶段收费金额
			chlr.setRechargeFixFee(null);//充值固定每笔收费
			chlr.setRechargeRate(null);//充值费率
		}
		//充值费率类型
		String rechargeType = chlr.getRechargeType();
		//充值费率--费率
		if("PERCENT".equalsIgnoreCase(rechargeType)){
			chlr.setRechargeStep(null);//充值阶段金额 
			chlr.setRechargeStepFee(null);//充值阶段收费金额
			chlr.setRechargeFixFee(null);//充值固定每笔收费
		}
		//充值费率-- 固定值
		if("FIXED".equalsIgnoreCase(rechargeType)){
			chlr.setRechargeStep(null);//充值阶段金额 
			chlr.setRechargeStepFee(null);//充值阶段收费金额
			chlr.setRechargeRate(null);//充值费率
		}
		//充值费率--阶梯费率
		if("STEP".equalsIgnoreCase(rechargeType)){
			chlr.setRechargeRate(null);//充值费率
			chlr.setRechargeFixFee(null);//充值固定每笔收费
		}
		//提现费率类型
		String withdrawType = chlr.getWithdrawType();
		//提现费率--费率
		if("PERCENT".equalsIgnoreCase(withdrawType)){
			chlr.setWithdrawFixFee(null);//提现固定每笔收费
			chlr.setWithdrawStep(null);//提现阶段金额 
			chlr.setWithdrawStepFee(null);//提现阶段收费金额
		}
		//提现费率-- 固定值
		if("FIXED".equalsIgnoreCase(withdrawType)){
			chlr.setWithdrawStep(null);//提现阶段金额 
			chlr.setWithdrawStepFee(null);//提现阶段收费金额
			chlr.setWithdrawRate(null);//提现费率
		}
		//提现费率--阶梯费率
		if("STEP".equalsIgnoreCase(withdrawType)){
			chlr.setWithdrawFixFee(null);//提现固定每笔收费
			chlr.setWithdrawRate(null);//提现费率
		}
		//根据机构编号获取规则ID
		String custRuleId = custRuleDao.selectPayCustRuleByPartnerNo(partner.getPartnerCode());
		chlr.setId(Long.valueOf(custRuleId));
		//修改规则
		custArDao.updateByPrimaryKey(chlr);
	}
	
	
	/**
	 * 修改机构基本信息
	 * @param partner
	 * @param payPartnerFileID
	 * @param userId
	 */
	public void updatePartner(PayPartner partner, List<Long> payPartnerFileID, long userId)  throws Exception{
		//机构编号
		String partnerCode = partner.getPartnerCode();
		//根据机构编号删除相关的机构与文件关联表中的信息
		payPartnerFileDao.deleteFileByPartnerNo(partnerCode);
		//更新机构基本信息
		int num = partnerDao.updateByPrimaryKeySelective(partner);
		//更新与协议相关表信息
		if(num > 0){
			if(payPartnerFileID != null && payPartnerFileID.size() > 0){
				for (Long partnerFileID : payPartnerFileID) {
					PayPartnerFile payPartnerFile = new PayPartnerFile();
					payPartnerFile.setPartnerNo(partnerCode);
					payPartnerFile.setFileId(partnerFileID);
					payPartnerFile.setOperator(userId);
					payPartnerFileDao.insertPartnerFile(payPartnerFile);
				}
			}
		}
	}
	
	/**
	 * 添加机构基本信息
	 * @param partner
	 * @param payPartnerFileID
	 * @param userId
	 */
	private void insertPartner(String partnerCode, PayPartner partner, List<Long> payPartnerFileID, long userId)  throws Exception{
		try {
			partner.setPartnerCode(partnerCode);
			partner.setPartnerStatus("WAITING_VALID");
			int result = partnerDao.insertPayPartner(partner);
			if(result > 0){
				if(payPartnerFileID != null && payPartnerFileID.size() > 0){
					for (Long partnerFileID : payPartnerFileID) {
						PayPartnerFile payPartnerFile = new PayPartnerFile();
						payPartnerFile.setPartnerNo(partnerCode);
						payPartnerFile.setFileId(partnerFileID);
						payPartnerFile.setOperator(userId);
						payPartnerFileDao.insertPartnerFile(payPartnerFile);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param chlr 渠道规则信息
	 */
	private void insertChlAr(ChlAcctRule chlr, String partnerCode)  throws Exception{
		chlr.setCreateTime(new Date());
		chlArDao.insert(chlr);
		Long chlRuleId = chlr.getId();
		//添加关联表信息
		PayChlRuleKey record = new PayChlRuleKey();
		record.setChlRuleId(chlRuleId);
		record.setPartnerNo(partnerCode);
		chlRuleDao.insertSelective(record);
	}

	/**
	 * @param custr 客户规则信息
	 */
	private void inserCustAr(CustAcctRule custr, String partnerCode)  throws Exception{
		custr.setCreateTime(new Date());
		custArDao.insert(custr);
		Long custRuleId = custr.getId();
		//添加关联表信息
		PayCustRuleKey record = new PayCustRuleKey();
		record.setCustRuleId(custRuleId);
		record.setPartnerNo(partnerCode);
		custRuleDao.insertSelective(record);
		
	}

	@Override
	public int selectPartnerByPartnerName(String partnerName) {
		return partnerDao.selectPartnerByPartnerName(partnerName);
	}

	@Override
	public List<PayPartner> selectAllValidPartnerName() {
		return partnerDao.selectAllValidPartnerName();
	}

	@Override
	public CustAcctRule selectCustRuleByPartnerNo(String partnerNo) {
		return custArDao.selectCustRuleByPartnerNo(partnerNo);
	}

	@Override
	public ChlAcctRule selectChlRuleByPartnerNo(String partnerNo) {
		return chlArDao.selectChlRuleByPartnerNo(partnerNo);
	}

	@Override
	public List<PayPartnerFile> selectFileByPartnerNo(String partnerNo) {
		return payPartnerFileDao.selectFileByPartnerNo(partnerNo);
	}

	@Override
	public List<NWFile> selectPartnerDetailFileByDetailId(long detailId) {
		List<NWFile> detailFiles=null;
		try {
			detailFiles=nwFileDao.selectPartnerDetailFileByDetailId(detailId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return detailFiles;
	}

	@Override
	public List<NWFile> selectPartnerFileByPartnerNo(String partnerCode){
		List<NWFile> partnerFiles=null;
		try {
			partnerFiles = nwFileDao.selectPartnerFileByPartnerNo(partnerCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return partnerFiles;
	}

}
